import { useStore } from '@/hooks';
import { Button, Checkbox, Dialog, Form, Input, Message, NumberPicker } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import { FieldsGrid } from '../stores/definitions.js';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import DrawerFooter from '@/components/DrawerFooter.jsx';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 14,
  },
  style: { marginBottom: 20 },
};

const tableId = uniqueId('tauTable-');

const SendCoupon = ({ activity, onCancel, modal, onSubmit, ...formProps }) => {
  const { activityStore: store } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [data] = useState(() => observable({}));
  const [state, setState] = useState([]);
  const [serviceListData, setServiceListData] = useState([]);
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量
  const [users, setUsers] = useState([]);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      editCtx.origin = _.cloneDeep(data);
      _.assign(data, activity);
      _.set(data, 'customerList', []);
      const res = await store.getActivityCustomer({ activityId: activity?.id });
      setUsers(res);
      await store.getCouponsApplies({ search: { activityIds: [activity?.id] } });
    })();
  }, []);

  if (!data) return <></>;

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = state.slice(startIndex, endIndex);

  const overrideModel = {
    customerMobile: {
      ui: {
        renderer: () => (
          <Input
            placeholder="请输入手机号"
            addonAfter={<Button type="primary" onClick={handleAddUser}>{t`添加客户`}</Button>}
          />
        ),
      },
    },
    serviceName: {
      ui: {
        renderer: (v) => (
          <TauSimpleSelect
            value={v}
            data={users}
          />),
      },
    },
    customerList: {
      ui: {
        renderer: (v) => (
          <TauSimpleSelect mode="multiple" value={v} data={serviceListData} />
        ),
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = async (values, item) => {
    const { name, value } = item;
    _.set(data, name, value);
    if (name === 'serviceName') {
      if (value) {
        const res = await store.getCouponBags({ search: { username: value } });
        setState(res);
      } else {
        setState([]);
      }
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleAddUser = async () => {
    const { customerMobile } = data;
    if (!customerMobile) {
      return Message.warning({ content: t`请输入手机号!` });
    }
    if (customerMobile.length !== 11) {
      return Message.warning({ content: t`请输入正确手机号!` });
    }
    const findUser = data?.customerList?.find((p) => p.startsWith(customerMobile));
    if (findUser) {
      return Message.warning({ content: t`该手机号已存在!` });
    }
    try {
      const res = await store.getUserMobile(customerMobile);
      if (res) {
        setServiceListData((pre) => {
          const arr = [...pre];
          arr.push({ label: res.fullname, value: res.username });
          return arr;
        });
        _.set(data, 'customerList', data.customerList.concat(res.username));
      } else {
        Message.error({ content: t`该用户非平台用户!` });
      }
    } catch (error) {
      Message.error({ content: t`添加失败`, duration: 7000 });
      throw error;
    }
  };

  /**
   * @description 提交表单实现修改用户
   * @param {*} r formData
   */
  const handleSubmit = async (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    let currentNext = false;
    state.forEach((item, i) => {
      const { totalQuantity, number, check } = item;
      if (check) {
        if (number === undefined || number === 0 || (number < 0) || (number > totalQuantity)) {
          currentNext = true;
          setState((pre) => {
            const toggle = [...pre];
            toggle[i].done = true;
            return toggle;
          });
        } else {
          setState((pre) => {
            const toggle = [...pre];
            toggle[i].done = false;
            return toggle;
          });
        }
      }
    });
    if (currentNext) {
      return Message.warning({ content: t`申请数量有误!` });
    }
    const { id: activityId, name: activityName, customerList: recipients, serviceName: issuer } = data;
    if (recipients?.length === 0) {
      return Message.warning({ content: t`接收客户不得为空!` });
    }
    const distributeBatchInfos = state.filter((p) => p.check !== false).map((item) => ({
      couponBatchId: item.couponBatchId,
      couponBatchName: item.couponBatchName,
      number: item.number,
    }));
    if (distributeBatchInfos?.length === 0) {
      return Message.error({ content: t`请勾选卡券发放批次!` });
    }
    const params = {
      activityId,
      activityName,
      recipients,
      issuer,
      distributeBatchInfos,
    };
    onSubmit?.(params);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      colon
      isPreview={false}
      {...formProps}
      value={data}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={data}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        columns={1}
        overrideModel={overrideModel}
        fields={(['serviceName', 'customerMobile', 'customerList'])}
      />
      <Form.Item
        label={t`发放批次列表`}
        labelAlign="top"
        name="batchList"
      >
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={currentPage}
          pageSize={pageSize}
          total={state.length}
          onFetch={({ page, size }) => {
            setCurrentPage(page);
            size && setPageSize(size);
          }}
          dataSource={currentPageData}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.priceIdx(i, currentPage, pageSize) },
            {
              title: t`批次名称`,
              dataIndex: 'couponBatchName',
              width: 200,
              cell: (v, _, r) => <span style={{ color: r?.done ? 'red' : '' }}>{v}</span>,
            },
            {
              title: t`总数量`,
              dataIndex: 'requestedQuantity',
              width: 168,
              cell: (v, _, r) => <span style={{ color: r?.done ? 'red' : '' }}>{v}</span>,
            },
            {
              title: t`使用数量`,
              dataIndex: 'conversionQuantity',
              width: 88,
              cell: (v, _, r) => <span style={{ color: r?.done ? 'red' : '' }}>{v}</span>,
            },
            {
              title: t`代发数量`,
              dataIndex: 'number',
              width: 200,
              cell: (v, i, r) => (
                <NumberPicker
                  onChange={(value) => setState((pre) => {
                    const toggle = [...pre];
                    toggle[i].number = value;
                    return toggle;
                  })}
                  value={v}
                  min={1}
                  isPreview={!r?.check}
                />
              ),
            },
            {
              title: t`选择`,
              dataIndex: 'check',
              cell: (v, i) => (<Checkbox
                checked={v}
                onChange={(c) => {
                  setState((pre) => {
                    const toggle = [...pre];
                    toggle[i].check = c;
                    return toggle;
                  });
                }}
              />),
            },
          ]}
        />
      </Form.Item>
      <DrawerFooter>
        <FromItem>
          <Form.Submit validate type="primary" onClick={handleSubmit}>{t`确定`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};


export default observer(SendCoupon);
